package com.cl.blog.web.manager;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cl.blog.common.Result;
import com.cl.blog.entity.BAdmin;
import com.cl.blog.entity.BNotice;
import com.cl.blog.service.BAdminService;
import com.cl.blog.service.BNoticeService;
import com.cl.blog.vo.NoticeSearchVo;
import com.cl.blog.vo.NoticeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author 付
 * @Date 2024-03-30 8:46
 * @Version 1.0
 * @description
 * @since 1.0
 */

@RestController
@RequestMapping("/admin/notice")
public class AdminNoticeController {

	@Autowired
	BNoticeService bNoticeService;
	@Autowired
	BAdminService bAdminService;

	@GetMapping("/list")
	public Result list() {
		List<BNotice> list = bNoticeService.list();
		for (BNotice bNotice : list) {
			BAdmin bAdmin = bAdminService.getById(bNotice.getAdminId());
			bNotice.setAdmin(bAdmin.getUsername());
		}

		return Result.success(list);
	}

	@PostMapping("/insert")
	public Result insertNotice(@Validated @RequestBody NoticeVo notice, HttpServletRequest request) {
		boolean b = bNoticeService.addNotice(notice, request);
		if (!b) {
			return Result.error("添加失败");
		}
		return Result.success();

	}

	@PostMapping("/remove")
	public Result remove(@RequestBody List<Integer> ids) {
		if (ids.size() <= 0) {
			return Result.error("抱歉，删除失败");
		}
		boolean b = bNoticeService.removeBatchByIds(ids);
		if (!b) {
			return Result.error("抱歉，删除失败");
		}

		return Result.success();
	}

	@PostMapping("/close")
	@Transactional(rollbackFor = Exception.class)
	public Result close(@RequestBody List<Integer> ids) {
		if (ids.size() <= 0) {
			return Result.error("抱歉，删除失败");
		}
		for (Integer id : ids) {
			bNoticeService.update(new UpdateWrapper<BNotice>()
					.eq("id", id)
					.set("status", 1)
			);
		}

		return Result.success();
	}

	@PostMapping("/search")
	public Result search(@RequestBody NoticeSearchVo noticeSearchVo) {
		if (noticeSearchVo.getAdmin().isEmpty()
				&& noticeSearchVo.getTitle().isEmpty()
				&& noticeSearchVo.getCreateTime() == null){
			return Result.error("抱歉，搜索添加不能为空");
		}

		List<BNotice> list = bNoticeService.searchNotice(noticeSearchVo);

		return Result.success(list);
	}

}
